<!DOCTYPE html>
<title>Test that unmuting offscreen video will not allow it to autoplay</title>
<script src="../resources/testharness.js"></script>
<script src="../resources/testharnessreport.js"></script>
<body>
<script>
  internals.settings.setAutoplayPolicy('user-gesture-required');
  internals.runtimeFlags.autoplayMutedVideosEnabled = true;

  async_test(function(t) {
    // Create a video off screen that will be unmuted before moving on screen.
    {
      var video = document.createElement('video');
      video.id = 'offscreen-unmute';
      video.src = 'content/test.ogv';
      video.muted = true;
      video.autoplay = true;
      video.loop = true;
      video.style.position = 'absolute';
      video.style.top = '-10000px';
      document.body.appendChild(video);
    }

    // Create a video off screen that will not be unmuted before moving on screen.
    {
      var video = document.createElement('video');
      video.id = 'offscreen-mute';
      video.src = 'content/test.ogv';
      video.muted = true;
      video.autoplay = true;
      video.loop = true;
      video.style.position = 'absolute';
      video.style.top = '-10000px';
      document.body.appendChild(video);
    }

    var offscreenUnmute = document.querySelector('#offscreen-unmute');
    var offscreenMute = document.querySelector('#offscreen-mute');
    var loaded = 0;

    function canPlayTroughHandler() {
      ++loaded;
      if (loaded != 2)
        return;

      assert_greater_than_equal(offscreenUnmute.readyState, HTMLMediaElement.HAVE_ENOUGH_DATA);
      assert_greater_than_equal(offscreenMute.readyState, HTMLMediaElement.HAVE_ENOUGH_DATA);

      offscreenUnmute.muted = false;
      offscreenUnmute.style.top = '0px';

      offscreenMute.style.top = '0px';
      offscreenMute.addEventListener('playing', t.step_func(_ => {
        setTimeout(t.step_func_done(_ => {
          assert_true(offscreenUnmute.paused);
          assert_false(offscreenMute.paused);
        }), 0);
      }));
    }

    offscreenUnmute.addEventListener('canplaythrough', t.step_func(canPlayTroughHandler));
    offscreenMute.addEventListener('canplaythrough', t.step_func(canPlayTroughHandler));
  });
</script>
</body>
